package com.qmyx.supply.admin.controller;

import com.aliyun.oss.OSSClient;
import com.qmyx.supply.admin.model.response.FileResponse;
import com.qmyx.supply.admin.utils.AliyunOSSClientUtil;
import com.ytjj.qmyx.supplychain.common.api.CommonResult;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import java.util.ArrayList;
import java.util.List;

/**
 * @Description TODO
 * @ClassName OssController
 *
 * 
 * @Version 1.0
 **/
@Slf4j
@RestController
@RequestMapping("/oss")
public class UploadController {

    /**
     * 单文件上传
     * @param file
     * @return
     */
    @PostMapping("/upload")
    public CommonResult getImgUrl(@RequestParam("file") MultipartFile file) {
        if (file.isEmpty()) {
            return CommonResult.failed("文件不存在！");
        }
        // 初始化OssClient
        OSSClient ossClient = AliyunOSSClientUtil.getOSSClient();
        log.info("开始上传文件 ===>" + file.getOriginalFilename());
        FileResponse fileResponse = AliyunOSSClientUtil.uploadObject2OSS(ossClient, file);
        if (fileResponse == null) {
            return CommonResult.failed("文件上传失败！");
        }
        return CommonResult.success(fileResponse);
    }

    /**
     * 多文件上传
     * @param file
     * @return
     */
    @PostMapping("/moreUpload")
    public CommonResult moreUpload(@RequestParam("file") MultipartFile[] file) {
        List<FileResponse> responseList = new ArrayList<>();
        for(MultipartFile img : file) {
            if (img.isEmpty()) {
                return CommonResult.failed("文件不存在！");
            }
            // 初始化OssClient
            OSSClient ossClient = AliyunOSSClientUtil.getOSSClient();
            log.info("开始上传文件 ===>" + img.getOriginalFilename());
            FileResponse fileResponse = AliyunOSSClientUtil.uploadObject2OSS(ossClient, img);
            if (fileResponse == null) {
                return CommonResult.failed("上传出现异常，请清空后重新上传！");
            }
            responseList.add(fileResponse);
        }
        return CommonResult.success(responseList);
    }
}
